package com.yulebaby.callsenter.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lzy.okgo.model.HttpParams;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.LoginBean;
import com.yulebaby.callsenter.database.manager.Dao;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.record.PhoneService;
import com.yulebaby.callsenter.task.LoginTask;
import com.yulebaby.callsenter.task.RequestSaleCallListTask;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.utils.JpushUtil;
import com.yulebaby.callsenter.utils.SPUtil;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.iv_logo)
    ImageView mIvLogo;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_login)
    ImageButton mBtnLogin;
    @BindView(R.id.activity_login)
    LinearLayout mActivityLogin;
    @BindView(R.id.et_username)
    EditText mEtUsername;


    private static final int PHONE_PERMISSION = 1000;
    private String mUsername;
    private String mPassword;
    private Dao mDao;
    private int User_Id = -1;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        checkPermiss();
    }

    @Override
    protected void initData() {
        mDao = Dao.getInstance();
        autoScrollView(mActivityLogin, mBtnLogin);
    }

    /**
     * 自滚动
     *
     * @param root
     * @param scrollToView
     */
    private void autoScrollView(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被遮挡的高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                //若不可视区域高度大于150，则键盘显示
                if (rootInvisibleHeight > 150) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域的底部
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }

    @OnClick(R.id.btn_login)
    public void onClick() {
        if (checkUsernameAndPassword(mEtUsername, mEtPassword)) {
            String preUsername = (String) SPUtil.get(Constant.USER_USERNAME, "");
            if (!TextUtils.isEmpty(preUsername) && !mUsername.equals(preUsername)) {
                mDao.deleteAllBean(CallLogBean.class);
                mDao.deleteAllBean(CustomerBean.class);
                SPUtil.remove(Constant.CUSTOMER_ALIAS);
            }
            requestLogin();
        }
    }

    /**
     * 请求这个销售之前所有的通话记录
     *
     * @param params
     */
    private void requstSaleCall(HttpParams params) {
        RequestSaleCallListTask.doRequestAllSaleCallList(this, params, new HttpCallback<List<CallLogBean>>() {
            @Override
            public void onSuccess(List<CallLogBean> result) {
                for (CallLogBean callLogBean : result) {
                    callLogBean.setIsUpdate(1);
                    if (TextUtils.isEmpty(callLogBean.getFile_path())) {
                        callLogBean.setPlayState(0);
                    } else {
                        callLogBean.setPlayState(2);
                    }
                }
                mDao.insertMultCallLogBean(result);
            }
        });
    }

    /**
     * 请求登录
     */
    private void requestLogin() {
        showLoading("登录中...");
        ProcessResult(new LoginBean("", 384, "yangyanlong", "213123", "123123124"));
        /*LoginTask.doLogin(this, mUsername, mPassword, new HttpCallback<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                ProcessResult(result);
            }

            @Override
            public void onFailParam(String info) {
                dismissLoading();
            }

            @Override
            public void onFail(String exception) {
                dismissLoading();
            }
        });*/
    }

    private void ProcessResult(LoginBean result) {
        SPUtil.save(Constant.USER_TOKEN, result.getToken());
        User_Id = result.getId();
        SPUtil.save(Constant.USER_ID, User_Id);
        SPUtil.save(Constant.USER_USERNAME, mUsername);
        //请求通话记录
        HttpParams params = new HttpParams();
        params.put("token", result.getToken());
        params.put("sale_id", User_Id);

        setAlias();

        requstSaleCall(params);

        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        startService(new Intent(LoginActivity.this, PhoneService.class));
        EventBus.getDefault().post(EventFactory.CreateRefreshEvent(RefreshEvent.refreshDataFromInternet));
        dismissLoading();
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 检查用户名和密码 只是非空校验 没有进行格式校验的添加
     *
     * @return
     */
    private boolean checkUsernameAndPassword(EditText etUser, EditText etPass) {
        mUsername = etUser.getText().toString().trim();
        mPassword = etPass.getText().toString().trim();
        if (TextUtils.isEmpty(mUsername)) {
            ToastUtil.showToast("用户名不能为空！");
            return false;
        }

        if (TextUtils.isEmpty(mPassword)) {
            ToastUtil.showToast("密码不能为空！");
            return false;
        }

        return true;
    }

    /**
     * Android 6.0 动态权限的校验
     */
    private void checkPermiss() {
        String[] perms = {
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.PROCESS_OUTGOING_CALLS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE};
        if (EasyPermissions.hasPermissions(LoginActivity.this, perms)) {
        } else {
            EasyPermissions.requestPermissions(this, "需要获取手机的权限", PHONE_PERMISSION, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    private void setAlias() {
        int customerAlias = (int) SPUtil.get(Constant.CUSTOMER_ALIAS, -1);
        if (customerAlias == -1 && User_Id != -1) {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, String.valueOf(User_Id)));
        }
    }


    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                case MSG_SET_TAGS:
                    break;
                default:
            }
        }
    };


    private TagAliasCallback mAliasCallback = (int code, String alias, Set<String> tags) -> {
        switch (code) {
            case 0:
                SPUtil.save(Constant.CUSTOMER_ALIAS, User_Id);
                SPUtil.save(Constant.REGISTER_ALIAS_SUCCESS, 1);
                break;

            case 6002:
                if (JpushUtil.isConnected(getApplicationContext())) {
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                } else {
                    SPUtil.remove(Constant.CUSTOMER_ALIAS);
                    SPUtil.save(Constant.REGISTER_ALIAS_SUCCESS, -1);
                }
                break;

            default:
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(0);
    }
}
